import 'package:aichat_flutter_wallet/module/module_create_wallet/pages/page_under_creation.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/button/public_button.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/header/page_header.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/public_tip/validate_tip.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_bitcoin_base/bitcoin_base.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_util/utils/utils.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../module_common/widgets/image/public_image.dart';
import '../../../module_common/widgets/public_tip/public_tip.dart';
import '../../../module_common/widgets/text_high_light.dart';

enum ImportWalletPageType {
  ResetPassword,
  ImportWallet,
  CreateOrImportWallet,
  ImportMPCWallet
}

class ImportWalletPage extends StatefulWidget {
  ImportWalletPageType type;

  ImportWalletPage(
      {super.key, this.type = ImportWalletPageType.CreateOrImportWallet});

  @override
  State<StatefulWidget> createState() {
    return _ImportWalletState();
  }
}

class _ImportWalletState extends State<ImportWalletPage>
    with TickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _rotationAnimation;
  bool _isRotated = false;

  final TextEditingController _passphraseController = TextEditingController();

  final TextEditingController _pathController = TextEditingController();
  FocusNode _pathFocusNode = FocusNode();

  final TextEditingController _secret_controller = TextEditingController();
  FocusNode _secret_focusNode = FocusNode();
  bool showSecretWarn = false;

  final TextEditingController _private_controller = TextEditingController();
  FocusNode _private_focusNode = FocusNode();
  bool showPrivateWarn = false;

  late TabController _tabController;

  bool btnDisabledStatus = true;

  Map<String, dynamic> get textMap {
    Map<String, dynamic> myMap = {};
    if (widget.type == ImportWalletPageType.CreateOrImportWallet) {
      myMap['title'] = 'Import Wallets';
    }
    if (widget.type == ImportWalletPageType.ResetPassword) {
      myMap['title'] = 'Reset Password';
      myMap['sub_title'] =
          'To change your password, we need you to import your private key or mnemonic phrase. Please makesure to backup the private key or mnemonicphrase of all your wallets before proceeding.';
    }
    if (widget.type == ImportWalletPageType.ImportMPCWallet) {
      myMap['title'] = '';
      myMap['mpc_title'] = 'Create your MPC wallet';
      myMap['mpc_sub_title'] =
          'Import a valid Recovery Phrase, Kai will create your MPC wallet via dual-entropy obfuscation algorithm';
    }
    if (widget.type == ImportWalletPageType.ImportWallet) {
      myMap['title'] = 'Import Wallets';
    }
    return myMap;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(_handleTabSelection);
    _controller = AnimationController(
      duration: Duration(milliseconds: 300),
      vsync: this,
    );

    // 创建平移动画
    _rotationAnimation =
        Tween<double>(begin: -0.5 * 3.14159, end: 0.5 * 3.14159)
            .animate(_controller);
  }

  void _handleTabSelection() {
    if (_tabController.indexIsChanging) {
      bool btnStatus = true;
      // 当选项卡正在发生切换时触发的操作】
      if (_tabController.index == 0) {
        btnStatus = _secret_controller.text.length <= 0;
        _private_focusNode.unfocus();
      } else if (_tabController.index == 1) {
        btnStatus = _private_controller.text.length <= 0;
        _secret_focusNode.unfocus();
      }
      setState(() {
        btnDisabledStatus = btnStatus;
      });
    }
  }

  Future<void> createWallet() async {
    if (btnDisabledStatus) return;
    String? key = _tabController.index == 1
        ? _private_controller.text
        : _secret_controller.text;
    if (_tabController.index == 0) {
      bool mnemonic = Utils.isMnemonic(key);
      if (!mnemonic) {
        setState(() {
          showSecretWarn = true;
        });
        return;
      } else {
        setState(() {
          showSecretWarn = false;
        });
      }
    }
    if (_tabController.index == 1) {
      bool privateKey = Utils.isPrivateKey(key);
      if (Utils.isBtcWifPrivateKey(key)) {
        key = SimpleBitcoin().convertWif2PrivateKeyHex(key);
        privateKey = true;
      }
      if (!privateKey) {
        setState(() {
          showPrivateWarn = true;
        });
        Toast.show(context,
            status: '2',
            position: Dpositon.bottom,
            message: 'Operation failed',
            duration: Duration(milliseconds: 2000));
        return;
      }
    }

    Map<String, dynamic> params = {};
    params['privateKey'] = key;
    // 初始化 导入 创建 账号
    if (widget.type == ImportWalletPageType.CreateOrImportWallet) {
      params['type'] = '2';
    }
    // 重置 密码
    if (widget.type == ImportWalletPageType.ResetPassword) {
      bool isValidTrue =
          await _checkWalletListFindKeyOrMnemonic(params['privateKey']);
      if (!isValidTrue) {
        Toast.show(context,
            status: '2',
            position: Dpositon.bottom,
            message: 'Operation failed',
            duration: Duration(milliseconds: 2000));
        return;
      }
      // 校验 用户 导入私钥 或者 助记词 是否 是 我们钱包助记词 中的 之一， 或者 是 私钥之一；
      params['type'] = '3';
    }
    // 导入 mpc 钱包助记词 生成 然后跳转页面
    if (widget.type == ImportWalletPageType.ImportMPCWallet) {
      // 替换当前页面 并返回
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
            builder: (context) => PageUnderCreation(
                  pk: params['privateKey'],
                  passphrase: _passphraseController.text.length > 0
                      ? _passphraseController.text
                      : null,
                  path: _pathController.text.length > 0
                      ? _pathController.text
                      : null,
                )),
      );
    }
  }

  Future<bool> _checkWalletListFindKeyOrMnemonic(String key) async {
    bool mnemonic = await Utils.isMnemonic(key);
    // 判断助记词 去找 钱包 列表 的私钥 解密 转化
    final walletList = await ObjectBox().walletModel.getSortedWalletList();
    List<String> keysLists = [];
    for (var i = 0; i < walletList.length; i++) {
      Wallet wallet = walletList[i];
      if (mnemonic) {
        // 所有 存储 的 walletList
        String walletKey = ObjectBox().decryptWalletKey(wallet.key);
        keysLists.add(walletKey);
      } else {
        keysLists.add(wallet.key);
      }
    }
    if (mnemonic) {
      return keysLists.contains(key);
    }
    return keysLists.contains(ObjectBox().encryptWalletKey(key));
  }

  @override
  void dispose() {
    _secret_focusNode.unfocus();
    _secret_focusNode.dispose();
    _secret_controller.dispose();
    // 选填项
    _pathController.dispose();
    _passphraseController.dispose();
    _pathFocusNode.dispose();
    // ---------------  助记词 ----------
    _private_focusNode.unfocus();
    _private_focusNode.dispose();
    _private_controller.dispose();
    // ---------------  私钥 ----------
    _tabController.removeListener(_handleTabSelection);
    _tabController.dispose();
    _controller.dispose();
    super.dispose();
  }

  Widget titleWidget(String title) {
    return Text(title,
        style: TextStyle(
            fontSize: 12.sp,
            fontWeight: FontWeight.w500,
            color: Color.fromRGBO(134, 131, 145, 1)));
  }

  Widget textInputControl({
    double? height,
    List<TextInputFormatter>? inputFormatters,
    int? maxLines = 1,
    String hintText = '',
    FocusNode? focusNode,
    TextEditingController? controller,
    TextInputAction? textInputAction,
    bool isDisabled = false,
    void Function()? onEditingComplete,
    void Function(String)? onChanged,
    void Function()? onTapOutside,
  }) {
    return Container(
      height: height,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8.w),
        color: Color.fromRGBO(246, 246, 246, 1),
      ),
      child: Stack(
        children: [
          TextField(
              cursorHeight: 20.w,
              readOnly: isDisabled,
              textInputAction: textInputAction,
              inputFormatters: inputFormatters,
              textAlign: TextAlign.justify,
              textAlignVertical: TextAlignVertical.top,
              controller: controller,
              focusNode: focusNode,
              onTapOutside: (PointDownEvent) {
                focusNode?.unfocus();
                if (onTapOutside != null) onTapOutside();
              },
              onEditingComplete: onEditingComplete,
              onChanged: onChanged,
              maxLines: maxLines,
              style: TextStyle(
                  color: Color.fromRGBO(51, 51, 51, 1),
                  fontWeight: FontWeight.w400,
                  fontSize: 14.sp,
                  height: 20.w / 14.w),
              decoration: InputDecoration(
                contentPadding: const EdgeInsets.all(15),
                border: InputBorder.none,
                hintText: hintText,
                hintStyle: TextStyle(
                  fontSize: 14.sp,
                  color: Color.fromRGBO(190, 189, 202, 1),
                ),
              )),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: PageHeaderCom(
          title: textMap['title'],
          showBottomBorder: false,
        ),
        backgroundColor: Colors.white,
        body: TabBarView(
          physics: NeverScrollableScrollPhysics(),
          controller: _tabController,
          children: [
            SingleChildScrollView(
              child: Padding(
                padding: EdgeInsets.only(top: 14.w, left: 20.w, right: 20.w),
                child: Column(
                  children: [
                    if (textMap['sub_title'] != null &&
                        textMap['sub_title'].length > 0)
                      Padding(
                        padding: EdgeInsets.only(bottom: 20.w),
                        child: Align(
                          child: Text(
                            textMap['sub_title'],
                            style: TextStyle(
                                fontSize: 12.sp,
                                fontWeight: FontWeight.w400,
                                height: 16.w / 12.w,
                                color: Color.fromRGBO(51, 51, 51, 1)),
                          ),
                        ),
                      ),
                    Visibility(
                        visible:
                            widget.type == ImportWalletPageType.ImportMPCWallet,
                        child: Column(
                          children: [
                            Row(
                              children: [
                                Text(
                                  textMap['mpc_title'],
                                  style: TextStyle(
                                      height: 26.w / 20.w,
                                      fontSize: 20.sp,
                                      fontWeight: FontWeight.w500,
                                      color: Color.fromRGBO(51, 51, 51, 1)),
                                ),
                              ],
                            ),
                            SizedBox(
                              height: 6.w,
                            ),
                            Row(
                              children: [
                                Expanded(
                                    child: TextHighlight(
                                        textMap['mpc_sub_title'],
                                        ['Recovery Phrase'],
                                        TextStyle(
                                            height: 16.w / 12.w,
                                            fontSize: 12.sp,
                                            fontWeight: FontWeight.w400,
                                            color: Color.fromRGBO(
                                                134, 131, 145, 1)),
                                        TextStyle(
                                            height: 16.w / 12.w,
                                            fontSize: 12.sp,
                                            fontWeight: FontWeight.w500,
                                            color:
                                                Color.fromRGBO(51, 51, 51, 1)),
                                        maxLines: null,
                                        overflow: TextOverflow.visible,
                                        searchContentClick: (int index) {},
                                        unSearchClick: () {})),
                              ],
                            ),
                            SizedBox(
                              height: 15.w,
                            ),
                          ],
                        )),
                    Container(
                      height: 90.w,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8.w),
                        color: Color.fromRGBO(246, 246, 246, 1),
                      ),
                      child: Stack(
                        children: [
                          TextField(
                            inputFormatters: [
                              FilteringTextInputFormatter.allow(
                                  RegExp("[a-zA-Z0-9 ]")),
                              // 只允许输入英文字符和空格
                            ],
                            textAlign: TextAlign.start,
                            textAlignVertical: TextAlignVertical.top,
                            controller: _secret_controller,
                            focusNode: _secret_focusNode,
                            onTapOutside: (PointDownEvent) {
                              _secret_focusNode.unfocus();
                              if (_secret_controller.text.length > 0) {
                                bool mnemonic = Utils.isMnemonic(_secret_controller.text);
                                if(mnemonic){
                                  btnDisabledStatus = false;
                                }else{
                                  btnDisabledStatus = true;
                                }
                              } else {
                                btnDisabledStatus = true;
                              }
                              setState(() {});
                            },
                            textInputAction: TextInputAction.done,
                            onEditingComplete: () {
                              _secret_focusNode.unfocus();
                            },
                            onChanged: (value) {
                              // 当选项卡正在发生切换时触发的操作】
                              // if (btnDisabledStatus == true &&
                              //     value.length > 0) {
                              //   setState(() {
                              //     btnDisabledStatus = false;
                              //   });
                              // }
                              // if (btnDisabledStatus == false &&
                              //     value.length <= 0) {
                              //   setState(() {
                              //     btnDisabledStatus = true;
                              //   });
                              // }
                            },
                            minLines: 2,
                            maxLines: 4,
                            style: TextStyle(
                                color: Color.fromRGBO(51, 51, 51, 1),
                                fontWeight: FontWeight.w400,
                                fontSize: 14.sp,
                                height: 18.w / 14.w),
                            decoration: InputDecoration(
                                contentPadding: EdgeInsets.all(15.w),
                                border: InputBorder.none,
                                hintText:
                                    'Please enter the recovery phrase in order, separated by spaces',
                                hintStyle: TextStyle(
                                    fontWeight: FontWeight.w400,
                                    fontSize: 14.sp,
                                    color: Color.fromRGBO(190, 189, 202, 1),
                                    height: 18.w / 14.w)),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 10.w,
                    ),
                    Visibility(
                        visible: showSecretWarn,
                        child: ValidateTip(
                            text: _secret_controller.text.isEmpty
                                ? 'Please provide your recovery phrase.'
                                : 'It is not a valid recovery phrase, please check it',
                            margin: EdgeInsets.zero,
                            onClose: () {
                              setState(() {
                                showSecretWarn = false;
                              });
                            })),
                    Visibility(
                        visible:
                            widget.type == ImportWalletPageType.ImportMPCWallet,
                        child: Column(
                          children: [
                            SizedBox(
                              height: 10.w,
                            ),
                            GestureDetector(
                              onTap: () {
                                setState(() {
                                  _isRotated = !_isRotated;
                                  if (_isRotated) {
                                    _controller.forward();
                                  } else {
                                    _controller.reverse();
                                  }
                                });
                              },
                              child: Row(
                                children: [
                                  Text(
                                    'Advanced (Optional)',
                                    style: TextStyle(
                                        fontWeight: FontWeight.w400,
                                        fontSize: 14.sp,
                                        color: Color.fromRGBO(134, 131, 145, 1),
                                        height: 16.w / 14.w),
                                  ),
                                  SizedBox(
                                    width: 5.w,
                                  ),
                                  AnimatedBuilder(
                                    animation: _controller,
                                    builder: (context, child) {
                                      return Transform.rotate(
                                        angle: _rotationAnimation.value,
                                        child: child,
                                      );
                                    },
                                    child: PublicImage(
                                      image:
                                          'assets/images/dapp/history_goback.png',
                                      width: 14.w,
                                      height: 14.w,
                                    ),
                                  )
                                ],
                              ),
                            ),
                            Visibility(
                                visible: _isRotated,
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    SizedBox(height: 20.w),
                                    titleWidget("Passphrase"),
                                    SizedBox(height: 10.w),
                                    textInputControl(
                                        height: 46.w,
                                        inputFormatters: [
                                          // FilteringTextInputFormatter.allow(
                                          //     RegExp("[a-zA-Z0-9]")),
                                          // 只允许输入英文大小写+数字
                                          LengthLimitingTextInputFormatter(16)
                                        ],
                                        hintText: 'Please enter the passphrase',
                                        maxLines: 1,
                                        controller: _passphraseController,
                                        textInputAction: TextInputAction.next,
                                        onEditingComplete: () {
                                          //点击confirm
                                          _pathFocusNode.nextFocus();
                                        }),
                                    SizedBox(height: 20.w),
                                    titleWidget("Path"),
                                    SizedBox(height: 10.w),
                                    textInputControl(
                                        height: 46.w,
                                        inputFormatters: [
                                          // FilteringTextInputFormatter.allow(
                                          //     RegExp("[a-zA-Z0-9]")),
                                          // 只允许输入英文大小写+数字
                                          // LengthLimitingTextInputFormatter(16)
                                        ],
                                        hintText: '0',
                                        maxLines: 1,
                                        focusNode: _pathFocusNode,
                                        controller: _pathController,
                                        textInputAction: TextInputAction.next,
                                        onEditingComplete: () {}),
                                    SizedBox(height: 15.w),
                                    InkWell(
                                      onTap: () {
                                        launchUrl(Uri.parse(
                                            'https://medium.com/@kaiwallet/how-to-create-kai-mpc-wallet-0ad81896662d'));
                                      },
                                      child: Row(
                                        children: [
                                          PublicImage(
                                            image:
                                                'assets/images/wallet/import_warn.png',
                                            width: 16.w,
                                            height: 16.w,
                                          ),
                                          SizedBox(
                                            width: 5.w,
                                          ),
                                          Expanded(
                                            child: Text(
                                              'How to create Kai MPC wallet',
                                              style: TextStyle(
                                                  fontSize: 14.sp,
                                                  fontWeight: FontWeight.w400,
                                                  color: Color.fromRGBO(
                                                      244, 101, 77, 1)),
                                            ),
                                          )
                                        ],
                                      ),
                                    ),
                                  ],
                                )),
                            SizedBox(
                              height: 30.w,
                            ),
                            Container(
                              padding: EdgeInsets.only(bottom: 10.w),
                              child: PublicButton(
                                  margin: EdgeInsets.zero,
                                  disabledStatus: btnDisabledStatus,
                                  type: ButtonType.private,
                                  text: 'Start to Create',
                                  onClick: () {
                                    createWallet();
                                  }),
                            ),
                          ],
                        ))
                  ],
                ),
              ),
            ),
            SingleChildScrollView(
              child: Padding(
                padding: EdgeInsets.only(top: 14, left: 20, right: 20),
                child: Column(
                  children: [
                    if (textMap['sub_title'] != null &&
                        textMap['sub_title'].length > 0)
                      Padding(
                        padding: EdgeInsets.only(bottom: 20),
                        child: Align(
                          child: Text(
                            textMap['sub_title'],
                            style: TextStyle(
                                fontSize: 12.sp,
                                fontWeight: FontWeight.w400,
                                height: 16 / 12,
                                color: Color.fromRGBO(51, 51, 51, 1)),
                          ),
                        ),
                      ),
                    Container(
                      height: 146,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8),
                        color: Color.fromRGBO(246, 246, 246, 1),
                      ),
                      child: Stack(
                        children: [
                          TextField(
                            inputFormatters: [
                              FilteringTextInputFormatter.allow(
                                  RegExp("[a-zA-Z0-9]")),
                              // 只允许输入英文字符和空格
                            ],
                            textAlign: TextAlign.justify,
                            textAlignVertical: TextAlignVertical.top,
                            controller: _private_controller,
                            minLines: 2,
                            maxLines: 4,
                            focusNode: _private_focusNode,
                            onTapOutside: (PointDownEvent) {
                              _private_focusNode.unfocus();
                            },
                            textInputAction: TextInputAction.done,
                            onEditingComplete: () {
                              _private_focusNode.unfocus();
                            },
                            onChanged: (value) {
                              // if (btnDisabledStatus == true && value.length > 0) {
                              //   setState(() {
                              //     btnDisabledStatus = false;
                              //   });
                              // }
                              // if (btnDisabledStatus == false && value.length <= 0) {
                              //   setState(() {
                              //     btnDisabledStatus = true;
                              //   });
                              // }
                            },
                            style: TextStyle(
                                color: Color.fromRGBO(51, 51, 51, 1),
                                fontWeight: FontWeight.w400,
                                fontSize: 14.sp,
                                height: 20 / 14),
                            decoration: InputDecoration(
                                contentPadding: const EdgeInsets.all(15),
                                border: InputBorder.none,
                                hintText: 'Please enter private key',
                                hintStyle: TextStyle(
                                    fontWeight: FontWeight.w400,
                                    fontSize: 14.sp,
                                    color: Color.fromRGBO(190, 189, 202, 1),
                                    height: 20 / 14)),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(
                      height: 10,
                    ),
                    Visibility(
                        visible: showPrivateWarn,
                        child: ValidateTip(
                            text:
                                'It is not a valid private key, please check it.',
                            margin: EdgeInsets.zero,
                            onClose: () {
                              setState(() {
                                showPrivateWarn = false;
                              });
                            }))
                  ],
                ),
              ),
            )
            // 第二个选项卡的内容
          ],
        ),
        bottomNavigationBar: widget.type == ImportWalletPageType.ImportMPCWallet
            ? null
            : Container(
                padding: EdgeInsets.only(bottom: 10),
                child: PublicButton(
                    disabledStatus: btnDisabledStatus,
                    type: ButtonType.private,
                    text: 'Confirm',
                    onClick: () {
                      createWallet();
                    }),
              ));
  }
}
